package activity;

import com.google.gson.Gson;
import enums.ActivityType;
import enums.ProductStatus;
import enums.ShowPosition;
import helper.CacheCallBack;
import helper.CacheHelper;
import models.BaseModel;
import models.admin.AdminUser;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import play.Logger;
import play.db.jpa.JPA;
import product.Product;
import product.merchant.ProductSpecMerchant;
import util.common.ConvertUtil;
import util.common.DateUtil;
import util.common.UStringUtil;

import javax.persistence.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by shancheng on 16-6-27.
 */
@Entity
@Table(name = "activity_prmotion_activity_products")
public class ActivityProduct extends BaseModel{

    public static final String CACHE_ACTIVITY_PRODUCT_BY_ACTIVITYID = "ULC_CACHE_ACTIVITY_PRODUCT_BY_ACTIVITY_ID_";

    /**
     * 促销活动信息
     */
    @JoinColumn(name = "activity_id")
    @ManyToOne
    public Activity activity;

    /**
     * 推荐商户
     */
    @JoinColumn(name = "merchant_id")
    @ManyToOne
    public Merchant merchant;

//
//    /**
//     * 关联产品
//     */
//    @JoinColumn(name = "product_spec_merchant_id")
//    @ManyToOne
//    public ProductSpecMerchant productSpecMerchant;

    /**
     * 关联产品
     */
    @JoinColumn(name = "product_id")
    @ManyToOne
    public Product product;

    /**
     * 活动价格
     */
    @Column(name = "activity_price")
    public Double activityPrice;

    /**
     * 活动前价格
     */
    @Column(name = "old_price")
    public Double oldPrice;


    /**
     * 排序
     */
    public String sort;

    /**
     * 产品图片
     */
    @Column(name = "img_path")
    public String imgSrc;
    /**
     * 逻辑删除状态
     */
    @Column(name = "deleted")
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;
    /**
     * 产品标题
     */
    @Column(name = "title")
    public String title;

    /**
     * 产品链接
     */
    @Column(name = "url")
    public String url;

    /**
     * PC端活动产品
     */
    @Column(name = "is_pc")
    public Boolean isPC;

//
//    /**
//     * 购物篮创建时间
//     */
//    @Column(name = "created_at")
//    public Date createdAt;
    /**
     * 根据展示位置,商户,查询
     * @param showPosition
     * @param merchantId
     * @return
     */
    public static List<ActivityProduct> findByActivityPosition(ShowPosition showPosition ,long  merchantId){
        return ActivityProduct.find(" activity.showPosition = ?1 and activity.merchant.id = ?2 and deleted = ?3",showPosition, merchantId ,DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 根据产品查询活动产品
     * @param productSpecMerchant
     * @return
     */
    public static ActivityProduct findByProductSpecMerchant(ProductSpecMerchant productSpecMerchant){
        return ActivityProduct.find(" productSpecMerchant = ?1 and deleted = ?2",productSpecMerchant,DeletedStatus.UN_DELETED).first();
    }
    public static ActivityProduct findByProductSpecMerchantId(long activityId,long id){
        return ActivityProduct.find(" productSpecMerchant.id = ?1 and deleted = ?2 and activity.id = ?3",id,DeletedStatus.UN_DELETED,activityId).first();
    }
    public static List<ActivityProduct> findByActivity(long id){
        return ActivityProduct.find("activity.id = ?1 and deleted = ?2 and product.id != null and product.productStatus = ?3 order by id asc",id,DeletedStatus.UN_DELETED, ProductStatus.UP).fetch();
    }
    public static ActivityProduct findByActivityAndProductSpecMerchantId(long activityId,long id){
        return ActivityProduct.find(" activity.id = ?1 and productSpecMerchant.id = ?2 and deleted = ?3 ",activityId,id,DeletedStatus.UN_DELETED).first();
    }
    /**
     * 删除图片
     * @param id
     */
    public static void deleteImg(long id){
        ActivityProduct activityProduct = ActivityProduct.findById(id);
        activityProduct.deleted = DeletedStatus.DELETED;
        activityProduct.save();
    }
    public static void deleteOnlyImg(long id){
        ActivityProduct activityProduct = ActivityProduct.findById(id);
        activityProduct.imgSrc = "";
        activityProduct.save();
    }
    public static void deleteByIds(Integer[] delItemArray,ShowPosition showPosition){
        String delItemStr = UStringUtil.concatStr(",", delItemArray);
        List<ActivityProduct> activityProducts = ActivityProduct.find(" productSpecMerchant.id in (" + delItemStr + ") and deleted = ?1 and activity.showPosition = ?2",DeletedStatus.UN_DELETED,showPosition).fetch();
        for(ActivityProduct activityProduct :activityProducts){
            activityProduct.deleted = DeletedStatus.DELETED;
            activityProduct.save();
        }
    }

    /**
     * 根据ID删除活动商品
     * @param delItemArray
     */
    public static void deleteByActivityProductIdIds(Integer[] delItemArray){
        String delItemStr = UStringUtil.concatStr(",", delItemArray);
        String sqlUpdate = "update activity_prmotion_activity_products a set a.deleted = 1 where a.id in ("+delItemStr+") ;";
        JPA.em().createNativeQuery(sqlUpdate).executeUpdate();
    }


    /**
     * 根据活动 拿到活动商品
     * @param activity
     * @return
     */
    public static List<ActivityProduct> findByActivityId(final Activity activity) {
        return CacheHelper.getCache(CACHE_ACTIVITY_PRODUCT_BY_ACTIVITYID + activity.id, new CacheCallBack<List<ActivityProduct>>() {
            @Override
            public List<ActivityProduct> loadData() {
                return ActivityProduct.find("deleted = ?1 and activity = ?2" , DeletedStatus.UN_DELETED , activity).fetch();
            }
        });
    }

    /**
     * 根据商品获取活动列表,目前的活动有秒杀有起始时间,所以目前只获取秒杀活动的item
     * @param specMerchantId
     */
    public static Boolean countActivityBySpecMerchantId(long specMerchantId,Date beginDate,Date endDate){
        String sqlSelect="select count(1) from activity_prmotion_activity_products a  " +
                " left join activity b on a.activity_id=b.id " +
                " left join product_spec_merchants c on a.product_spec_merchant_id=c.id " +
                " where c.id=%s " +
                " and a.deleted=%s " +
                " and b.deleted=%s " +
                " and b.type='%s' " +
                " and ((b.begin_at>='%s' and b.begin_at<='%s') or (b.end_at>='%s' and b.end_at<='%s')) ";
        String sqlCount=String.format(sqlSelect,specMerchantId,DeletedStatus.UN_DELETED.getValue(),DeletedStatus.UN_DELETED.getValue(),ActivityType.MIAOSHA,DateUtil.dateToString(beginDate,"yyyy-MM-dd"),DateUtil.dateToString(endDate,"yyyy-MM-dd"),DateUtil.dateToString(beginDate,"yyyy-MM-dd"),DateUtil.dateToString(endDate,"yyyy-MM-dd"));

        return ConvertUtil.toLong(ActivityProduct.em().createNativeQuery(sqlCount).getSingleResult())>0;
    }

    /**
     * 根据productSpecMerchantId数组,获取ActivityProduct集合
     * @param specMerchantIdArrays
     */
    public static List<Map<String,Object>> loadBySpecMerchantId(Integer[] specMerchantIdArrays){
        String specMerchantIds=UStringUtil.concatStr(",",specMerchantIdArrays);
        String sqlSelect="select * from activity_prmotion_activity_products a  " +
                " left join activity b on a.activity_id=b.id " +
                " left join product_spec_merchants c on a.product_spec_merchant_id=c.id " +
                " where a.deleted=  " +DeletedStatus.UN_DELETED.getValue()+
                " and b.deleted="+DeletedStatus.UN_DELETED.getValue()+
                " and b.show_position <>'"+ShowPosition.INDEX_PROMOTION+"' " +
                " and c.id in( "+specMerchantIds+")";
        Query query=ActivityProduct.em().createNativeQuery(sqlSelect);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        return query.getResultList();
    }

    /**
     * 根据Id查询活动商品
     * @param id
     * @return
     */
    public static ActivityProduct findByActivityProductId(long id){
        return  ActivityProduct.find(" id = ?1 and deleted = ?2 " , id , DeletedStatus.UN_DELETED).first();
    }

    /**
     * 根据活动ID删除活动下的活动商品
     * @param activityId
     */
    public static void deletedByActivityId(long activityId){
        String sqlUpdate = " update activity_prmotion_activity_products a set a.deleted = 1 where a.activity_id = "+activityId ;
        JPA.em().createNativeQuery(sqlUpdate).executeUpdate();
    }


    /**
     * 保存头条
     * @param activity
     * @param activityProduct
     * @param loginUser
     */
    public static void saveActivityProductForNotice(Activity activity , ActivityProduct activityProduct , AdminUser loginUser){

        if (activityProduct.id == null) {
            if (StringUtils.isNotBlank(activityProduct.title)) {
                ActivityProduct newProduct = new ActivityProduct();
                newProduct.title = activityProduct.title;
                newProduct.createAt = new Date();
                newProduct.creator = loginUser;
                newProduct.deleted = DeletedStatus.UN_DELETED;
                newProduct.activity = activity;
                newProduct.save();
            }
        } else {
            activityProduct.modifier = loginUser;
            activityProduct.modifyAt = new Date();
            activityProduct.save();

        }

    }

    /**
     * 保存产品
     * @param activity
     * @param activityProduct
     * @param loginUser
     */
    public static void saveActivityProductForProduct(Activity activity , ActivityProduct activityProduct , AdminUser loginUser){
        Logger.info("activityProduct.id :%s , activityProduct.product: %s",  activityProduct.id,new Gson().toJson( activityProduct.product));
        if (activityProduct.id == null) {
            if (activityProduct.product != null) {
                activityProduct.creator = loginUser;
                activityProduct.createAt = new Date();
                activityProduct.activity = activity;
                activityProduct.deleted = DeletedStatus.UN_DELETED;
                activityProduct.save();
            }
        } else {
            activityProduct.modifier = loginUser;
            activityProduct.modifyAt = new Date();
            if(activityProduct.product == null){
                activityProduct.deleted = DeletedStatus.DELETED;
            }
            activityProduct.save();

        }
    }

    /**
     * 保存推荐商户
     * @param activity
     * @param activityProduct
     * @param loginUser
     */
    public static void saveActivityProductForMerchant(Activity activity , ActivityProduct activityProduct , AdminUser loginUser){
        if(activityProduct.id == null){
            if(activityProduct.merchant != null){
                activityProduct.deleted = DeletedStatus.UN_DELETED ;
                activityProduct.activity = activity ;
                activityProduct.createAt = new Date();
                activityProduct.creator = loginUser ;
                activityProduct.ctDept = loginUser.ctDept != null ?  loginUser.ctDept : null;
                activityProduct.save();
            }
        }else {
            if(activityProduct.merchant == null ){
                activityProduct.deleted = DeletedStatus.DELETED ;
            }
            activityProduct.modifier = loginUser ;
            activityProduct.modifyAt = new Date();
            activityProduct.save();
        }
    }
    public static List<ActivityProduct> findByActivityProduct(long id){
        return ActivityProduct.find("activity.id = ?1 and deleted = ?2  order by id asc",id,DeletedStatus.UN_DELETED).fetch();
    }


    /**
     * 根据商品Id删除活动明细
     * @param productId
     */
    public static void deletedByProductId(long productId){
        String sqlUpdate = " update activity_prmotion_activity_products a set a.deleted = 1 where a.product_id = "+productId ;
        JPA.em().createNativeQuery(sqlUpdate).executeUpdate();
    }


}
